package com.xv.yan.servlet;

import com.xv.yan.beans.entity.AdminDo;
import com.xv.yan.service.AdminService;
import com.xv.yan.service.impl.AdminServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "loginServlet", value = "/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String type = request.getParameter("type");

        if ("trueLogin".equals(type)) {  //执行登录  登录就登录  不登录就else
            String  userName= request.getParameter("userName");
            String pwd= request.getParameter("pwd");
            System.out.println("表单传过来的："+userName+"#"+pwd);
            if (userName == null || "".equals(userName.trim()) || pwd == null || "".equals(pwd.trim())){
                request.setAttribute("message","用户名或密码不能为空");
                request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);
                return;

            }
            AdminService adminService=new AdminServiceImpl();
            AdminDo adminDo = adminService.validateLogin(userName);

            System.out.println("数据库查到的"+userName+" 密码:"+ adminDo.getPwd());
            if (adminDo != null && pwd.equals(adminDo.getPwd())){
                //放在session之前清空敏感信息
                adminDo.setPwd(null);
                request.getSession().setAttribute("adminDo",adminDo);
                //当我们做了提交表单的动作后再通过getRequestDispatcher进行内部转发
                //刷新页面会导致表单的重复提交
                //这时候我们可以用重定向去替代，但是重定向不能访问WEB-INF下面的
                //所以要宰新建一个servlet，再内部转发到jsp里面
                response.sendRedirect("/StudentServlet?type=toStudentManage");
            }else {
                /**
                 *
                 * 这样的页面转发我不会
                 * 我写的都没用转发，这个和数据库的联系在哪里呀，   刚才没有连接数据库的时候是可以运行的
                 * 只有核对登录的账号密码的时候才有联系   跟页面出现不出没有关系，哦，那我改一下
                 */
                request.setAttribute("message","用户名或密码不正确");
                request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);
            }
        }else {
            request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
